<template>
  <div class="employees-page">
    <h2>员工管理</h2>

    <!-- 操作栏 -->
    <div class="action-bar">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="搜索">
          <el-input 
            v-model="filterForm.keyword" 
            placeholder="用户名或姓名" 
            clearable 
            @clear="handleSearch"
            @keyup.enter="handleSearch"
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="全部状态" clearable @change="handleSearch" style="width: 120px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
      
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 添加员工
      </el-button>
    </div>

    <!-- 员工列表 -->
    <el-table v-loading="loading" :data="employees" stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column prop="phone" label="手机号" width="130" />
      <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
      <el-table-column prop="address" label="地址" min-width="150" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-button 
            :type="row.status === 1 ? 'warning' : 'success'" 
            size="small" 
            link 
            @click="handleToggleStatus(row)">
            <el-icon><Switch /></el-icon> {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button type="info" size="small" link @click="handleResetPassword(row)">
            <el-icon><Key /></el-icon> 重置密码
          </el-button>
          <el-button type="danger" size="small" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="employeeForm" 
        :rules="employeeRules" 
        ref="employeeFormRef" 
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="employeeForm.username" 
            placeholder="请输入用户名（4-20位字母、数字或下划线）"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input 
            v-model="employeeForm.password" 
            type="password" 
            placeholder="请输入密码（6-20位）"
            show-password
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="employeeForm.name" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="employeeForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="employeeForm.email" placeholder="请输入邮箱（选填）" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input 
            v-model="employeeForm.address" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入地址（选填）"
          />
        </el-form-item>
        <el-form-item v-if="isEdit" label="状态" prop="status">
          <el-radio-group v-model="employeeForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog 
      v-model="passwordDialogVisible" 
      title="重置密码" 
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="passwordForm" 
        :rules="passwordRules" 
        ref="passwordFormRef" 
        label-width="100px"
      >
        <el-form-item label="员工">
          <el-input :value="currentEmployee.name + '（' + currentEmployee.username + '）'" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            placeholder="请输入新密码（6-20位）"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmitPassword">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getEmployeeList, 
  createEmployee, 
  updateEmployee, 
  deleteEmployee,
  toggleEmployeeStatus,
  resetPassword
} from '@/api/employee'

const loading = ref(false)
const employees = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const filterForm = reactive({
  keyword: '',
  status: null
})

const dialogVisible = ref(false)
const isEdit = ref(false)
const employeeForm = ref({
  username: '',
  password: '',
  name: '',
  phone: '',
  email: '',
  address: '',
  status: 1
})
const employeeFormRef = ref(null)
const submitting = ref(false)

const passwordDialogVisible = ref(false)
const currentEmployee = ref({})
const passwordForm = ref({
  newPassword: '',
  confirmPassword: ''
})
const passwordFormRef = ref(null)

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑员工' : '添加员工'
})

// 表单验证规则
const employeeRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]{4,20}$/, message: '用户名必须是4-20位字母、数字或下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20位之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
}

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20位之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 加载员工列表
const loadEmployees = async () => {
  loading.value = true
  try {
    const res = await getEmployeeList({
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: filterForm.keyword,
      status: filterForm.status
    })
    if (res.code === 200) {
      employees.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '加载员工列表失败')
    }
  } catch (error) {
    console.error('加载员工列表失败', error)
    ElMessage.error('加载员工列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadEmployees()
}

// 重置
const handleReset = () => {
  filterForm.keyword = ''
  filterForm.status = null
  currentPage.value = 1
  loadEmployees()
}

// 分页变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadEmployees()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadEmployees()
}

// 添加员工
const handleAdd = () => {
  isEdit.value = false
  employeeForm.value = {
    username: '',
    password: '',
    name: '',
    phone: '',
    email: '',
    address: '',
    status: 1
  }
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = (row) => {
  isEdit.value = true
  employeeForm.value = {
    id: row.id,
    username: row.username,
    name: row.name,
    phone: row.phone,
    email: row.email,
    address: row.address,
    status: row.status
  }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!employeeFormRef.value) return
  
  await employeeFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        let res
        if (isEdit.value) {
          res = await updateEmployee(employeeForm.value.id, employeeForm.value)
        } else {
          res = await createEmployee(employeeForm.value)
        }
        
        if (res.code === 200) {
          ElMessage.success(res.message || (isEdit.value ? '更新成功' : '创建成功'))
          dialogVisible.value = false
          loadEmployees()
        } else {
          ElMessage.error(res.message || (isEdit.value ? '更新失败' : '创建失败'))
        }
      } catch (error) {
        console.error('提交失败', error)
        ElMessage.error('提交失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 启用/禁用员工
const handleToggleStatus = (row) => {
  const action = row.status === 1 ? '禁用' : '启用'
  ElMessageBox.confirm(`确定要${action}该员工吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await toggleEmployeeStatus(row.id)
      if (res.code === 200) {
        ElMessage.success(`${action}成功`)
        loadEmployees()
      } else {
        ElMessage.error(res.message || `${action}失败`)
      }
    } catch (error) {
      console.error(`${action}失败`, error)
      ElMessage.error(`${action}失败`)
    }
  }).catch(() => {})
}

// 重置密码
const handleResetPassword = (row) => {
  currentEmployee.value = row
  passwordForm.value = {
    newPassword: '',
    confirmPassword: ''
  }
  passwordDialogVisible.value = true
}

// 提交密码重置
const handleSubmitPassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const res = await resetPassword(currentEmployee.value.id, {
          newPassword: passwordForm.value.newPassword
        })
        if (res.code === 200) {
          ElMessage.success('密码重置成功')
          passwordDialogVisible.value = false
        } else {
          ElMessage.error(res.message || '密码重置失败')
        }
      } catch (error) {
        console.error('密码重置失败', error)
        ElMessage.error('密码重置失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除员工
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该员工吗？删除后将无法恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    try {
      const res = await deleteEmployee(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadEmployees()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  loadEmployees()
})
</script>

<style scoped lang="scss">
.employees-page {
  padding: 20px;

  h2 {
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
  }

  .action-bar {
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
  }

  .el-table {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
